package com.codes.controller;

import com.alibaba.fastjson.JSON;
import com.codes.core.common.result.Result;
import com.codes.core.model.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Controller基类   暂时不用 (用来做全局 异常处理
 *
 * @author peanut
 * @date 2020/05/22 11:41
 */
@Slf4j
@RestControllerAdvice
public class BaseController {

    /**
     * 全局异常捕获
     */
    @ExceptionHandler(Exception.class)
    public Result exceptionHandle(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        try {
            StringWriter errors = new StringWriter();
            ex.printStackTrace(new PrintWriter(errors));
            log.error("downalod exception:"+ex.getMessage()+"\t"+errors.toString());
            // 如果为异步请求，返回ApiResponse对象
//            if (this.isAjax(request)) {
//                response.setHeader("content-type", "text/html;charset=UTF-8");
//                response.getWriter().write(JSON.toJSONString(ApiResponse.failed(ex.getMessage())));
//                return null;
//            }
            return Result.error(ex.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
          return Result.error(e.getMessage());
        }
    }

    /**
     * 判断请求是否为异步  异步
     */
    private boolean isAjax(HttpServletRequest request) {
        return StringUtils.isNotBlank(request.getHeader("X-Requested-With"));
    }
}